"""
@author: yinjx
@file: lianxi-sanlelogging.py
@time: 2023/6/11 19:15
"""
import json
import logging

# 配置logging模块
logging.basicConfig(filename='shopping.log', level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(message)s')

gds_info = {"#F00001":{"name":"apple","price":1.4},
            "#F00002":{"name":"banana","price":2},
            "F00003":{"name":"梨子","price":4},
            "F00004":{"name":"桃子","price":5},
            "F00005":{"name":"蟹黄面","price":30},
            "F00006":{"name":"部队火锅","price":25}
            }

def register():
    fp = open("cs.txt", "r")
    readl = fp.read()
    readl = json.loads(readl)
    fp.close()
    name = input("请输入您要注册的用户名：")
    passwd = input("请输入您的用户名密码：")
    readl[name] = passwd
    readl = json.dumps(readl)
    fp = open("cs.txt", "w")
    fp.write(readl)
    fp.close()
    logging.info(f"用户{name}注册成功")
    print("注册成功，请重新登入")
    login()

def login():
    fp = open("cs.txt", "r")
    readl = fp.read()
    readl = json.loads(readl)
    fp.close()
    name = input("欢迎登入三乐系统，请输入你的用户名：")
    passwd = input("请输入你的密码：")
    if readl.get(name) == passwd:
        logging.info(f"用户{name}登入成功")
        print("登入成功")
    else:
        logging.warning(f"用户{name}登入失败")
        print("用户名或密码输入错误")
        login()

def buy(money):
    lst = []
    dict1 = {}
    while True:
        gs = input("请输入您要购买的物品的编号和物品数量（请以空格隔开输入），若要查看购物车请输入1，若要结算请输入q：")
        if gs == "q":
            if sum(lst) > money:
                num = input("预算不够，是否修改您的购物车(yes/no)？")
                if num == "yes":
                    a = "0"
                    while a == "0":
                        logging.info("进入购物车修改模式")
                        print(dict1)
                        re1 = input("请输入您要修改物品的编号：")
                        re2 = int(input("请输入您要修改的物品的数量："))
                        if re2 == 0:
                            dict1.pop(re1)
                        else:
                            price = gds_info[re1]["price"]
                            if re1 in dict1:
                                gd = dict1[re1]
                                gd["num"] = re2
                                sprice = re2 * price
                                gd["sprice"] = sprice
                            else:
                                name = gds_info[re1]["name"]
                                sprice = re2 * price
                                dict1[re1] = {"name":name,"num":re2,"sprice":sprice}
                        print(dict1)
                        a = input("是否继续修改购物车（继续请输入0，结算请输入其他字符）：")
                        if a != "0":
                            l = 0
                            for k,i in dict1.items():
                                l = i["sprice"] + l
                                print(f"您购买的物品{i['name']}  数量为:{i['num']}  总价为:{i['sprice']}")
                            money -= l
                            logging.info(f"本次购物消费{sum(lst)}元，余额为{money}元")
                            print(f'总计为:{l},余额为:{money}')
                            return 1
                else :
                    logging.info("用户购物结束")
                    print("本次购物结束")
                    return 1
            else:
                money -= sum(lst)
                logging.info(f"本次购物消费{sum(lst)}元，余额为{money}元")
                print(f"总消费为：{sum(lst)}，余额为：{money}")
                return 1
            break
        elif gs == "1":
            for k , v in dict1.items():
                print(f'您购买的物品:{v["name"]} 数量为:{v["num"]}  总价钱为:{v["sprice"]}')
            money -= sum(lst)
            logging.info(f"购物车内物品信息：{dict1}，总计为{sum(lst)},余额为{money}")
            print(f'总计为：{sum(lst)},余额为:{money}')
        else:
            gs = gs.split(" ")
            num = int(gs[1])
            w = gs[0]
            wp = gds_info[w]
            price = wp["price"]
            name = wp["name"]
            sprice = price * num
            lst.append(sprice)
            if w in dict1:
                s = dict1[w]
                s["num"] = s["num"] + num
                s["sprice"] = s["sprice"] + sprice
            else:
                dict1[w] = {"name":name, "num": num, "sprice": sprice}

while True:
    num = input("请输入你的选择\n1.登入\n2.注册\n3.输入其他字符退出\n")
    if num == "1":
        login()
    elif num == "2":
        register()
    else:
        break

    money = int(input("请输入您的预算："))
    print("以下是我们三乐超市的物品清单：")
    for k,v in gds_info.items():
        print(f'编号:{k}   {v["name"]}  的价格是  {v["price"]}')

    a = buy(money)
    if a == 1:
        logging.info("本次购物结束")
        print('本次购物结束')
        break
